import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment, { isDate } from 'moment';
import router from 'umi/router';
import Media from 'react-media';
import AntdInput from '@/components/AntdInput';
import AntdFormItem from '@/components/AntdFormItem';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Radio,
  Button,
  Collapse,
  DatePicker,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import AntdUpload from '@/components/AntdUpload';
import SearchSelect from '@/components/SearchSelect';
import { columns1, supplierColumns } from '@/pages/Common/common';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile, queryDict } from '@/utils/common';

import styles from '@/pages/Operate.less';
import AntdDatePicker from '@/components/AntdDatePicker';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import { allDictList } from '@/utils/constans';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
@connect(({ tmsOilCard, component, loading }) => ({
  tmsOilCard,
  // dictObject: common.dictObject,
  dictObject: component.dictObject,
  loading: loading.effects['tmsOilCard/selectDetails'],
}))
@Form.create({
  onValuesChange(props) {},
})
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      fileList: [],
      activeKey: ['1'],
      deleteFileIds: [],
      ownCompany: '',
      sellCompany: '',
      selectCardType: 'MASTER',
      cars: [],
      company: [],
      disabled: false,
      masterCardList: [],
    };
    this.fileList = [];
  }
  componentDidMount() {
    const {
      tmsOilCard: { selectDetails },
      match: {
        params: { id },
      },
    } = this.props;

    this.getMasterCard();

    if (id) {
      this.getSelectDetails(id);
      this.queryFileList(id);
    } else {
      this.props.form.resetFields();
    }
  }

  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.currencyType, allDictList.saleCompany];
    queryDict({ props: this.props, allDict });
  }
  //详情信息：
  getSelectDetails = ID => {
    this.props.dispatch({
      type: 'tmsOilCard/selectDetails',
      payload: { id: ID },
      callback: data => {
        data && this.setFileList(data.attachments);
        this.setState({
          cars: [{ id: data.vehicleId }],
          selectCardType: data.cardType || this.state.selectCardType,
          sellCompany: data.sellCompanyCode,
          company: [{ customerCode: data.mdsCompanyId, customerName: data.mdsCompanyName }],
        });
      },
    });
  };

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'CARD_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  setFileList = fileList => {
    this.setState({ fileList });
  };

  getSelectList = (type, val) => {
    const { dispatch } = this.props;
    let params = {};
    if (type == 'search') {
      params = val;
    }
    params.currentPage = 1;
    dispatch({
      type: 'tmsOilCard/selectList',
      payload: params,
    });
  };

  //保存基本信息：
  saveBasicInfo = e => {
    e.stopPropagation();
    const { fileList, deleteFileIds, cars, company } = this.state;
    const {
      match: { params },
      dispatch,
    } = this.props;

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const { vehicleId, happenTime, fileTokens, ...value } = values;

      value.happenTime = happenTime ? moment(happenTime).format(dateFormat) : '';
      //编辑时传入id
      if (params.id) {
        value.id = params.id;
      }
      value.fileTokens = filterAddFile(fileTokens);
      value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);

      if (value.cardType && value.cardType === 'MASTER') {
        value.mdsCompanyId = company[0].customerCode || '';
        value.mdsCompanyName = company[0].customerName || '';
      } else {
        value.vehicleId = cars[0].id || '';
        value.mdsCompanyId = cars[0].ownCompanyId || '';
        value.mdsCompanyName = cars[0].ownCompanyName || '';
      }

      this.props.dispatch({
        type: 'tmsOilCard/oilCardOperate',
        payload: value,
        callback: res => {
          this.queryFileList(res);
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
          dispatch({
            type: 'tmsOilCard/selectDetails',
            payload: { id: res },
            callback: data => {
              this.setState({ cars: [{ id: data.vehicleId }] });
              if (!params.id) {
                dispatch({
                  type: 'common/setTabsName',
                  payload: {
                    id: res,
                    name: data.cardNo,
                    isReplaceTab: true,
                  },
                  callback: result => {
                    if (result) {
                      router.push(`/carBasic/oilCardList/edit-form/${res}`);
                    }
                  },
                });
              }
            },
          });
          this.getSelectList();
        },
      });
    });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };
  // 发售公司
  getSellComValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };
  // 选择副卡
  getCardTypeValue = (values, type) => {
    this.setState({
      [type]: values.target.value,
      cars: [],
      company: [],
    });
  };
  // 所属公司
  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
    if (type === 'cars') {
      values.map(v => {
        this.setState({
          ownCompany: v.ownCompanyName,
        });
      });
    }
  };
  //获取主卡号：
  getMasterCard() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tmsOilCard/selectMasterCardList',
      payload: {},
      callback: data => {
        this.setState({
          masterCardList: data || [],
        });
      },
    });
  }

  render() {
    const {
      selectedRowKeys,
      disabled,
      selectedRows,
      visible,
      fileList,
      ownCompany,
      cars,
      sellCompany,
      selectCardType,
      masterCardList,
    } = this.state;

    const {
      tmsOilCard: { selectDetails },
      form: { getFieldDecorator },
      dictObject,
      match: {
        params: { id },
      },
    } = this.props;
    const details = id ? selectDetails[id] : {};
    const checkDisabled = id ? true : false;

    const vehicleList = [];
    const commonParams = {
      getFieldDecorator,
    };
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{details ? details.cardNo : '新增油卡'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={id ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.saveBasicInfo(e)}
              text="保存"
              code={details ? codes.edit : codes.add}
            />
            {id && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={id ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const prefixSelector = () => (
      <AntdFormItem
        code="currencyType"
        initialValue={details && details.currencyType ? details.currencyType : 'CNY'}
        {...commonParams}
      >
        <Select style={{ width: 120 }} disabled={disabled || (details && details.currencyType)}>
          {dictObject[allDictList.currencyType] &&
            dictObject[allDictList.currencyType].map(item => (
              <Option key={item.code}>{item.value}</Option>
            ))}
        </Select>
      </AntdFormItem>
    );
    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="油卡信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="卡号">
                        {getFieldDecorator('cardNo', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: details ? details.cardNo : '',
                        })(<Input placeholder="请输入" disabled={disabled || checkDisabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <AntdFormItem
                        code="sellCompanyCode"
                        label="发售公司"
                        initialValue={details ? details.sellCompanyCode : undefined}
                        {...commonParams}
                      >
                        <Select
                          placeholder="请选择"
                          allowClear={true}
                          disabled={disabled}
                          onChange={values => this.getSellComValue(values, 'sellCompany')} // 获取选中值
                          disabled={disabled || checkDisabled}
                        >
                          {dictObject[allDictList.saleCompany] &&
                            dictObject[allDictList.saleCompany].map(item => (
                              <Option key={item.code}>{item.value}</Option>
                            ))}
                        </Select>
                      </AntdFormItem>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <AntdFormItem
                        label="充值金额"
                        code="currentMoney"
                        rules={[{ required: true, message: '请输入' }]}
                        initialValue={details ? details.currentMoney : undefined}
                        getFieldDecorator={getFieldDecorator}
                      >
                        <AntdInput
                          mode="money"
                          placeholder="输入数字,可保留两位小数,长度不超过18位"
                          addonBefore={prefixSelector()}
                          disabled={disabled || checkDisabled}
                        />
                      </AntdFormItem>
                    </Col>
                    {sellCompany == 'SINOPEC' && (
                      <Col md={12} sm={24}>
                        <AntdFormItem
                          label="油卡类型"
                          code="cardType"
                          initialValue={details && details.cardType ? details.cardType : 'MASTER'}
                          //initialValue={"MASTER"}
                          rules={[{ required: false }]}
                          {...commonParams}
                        >
                          <Radio.Group
                            onChange={values => this.getCardTypeValue(values, 'selectCardType')}
                            disabled={disabled}

                            // disabled={checkId ? true : false}
                          >
                            <Radio value="SLAVE" disabled={disabled}>
                              副卡
                            </Radio>
                            <Radio value="MASTER" disabled={disabled}>
                              主卡
                            </Radio>
                          </Radio.Group>
                        </AntdFormItem>
                      </Col>
                    )}
                  </Row>

                  {/* 选择中国石化，并且是主卡类型的才是所属公司必填 */}
                  {sellCompany == 'SINOPEC' && selectCardType == 'MASTER' ? (
                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                      <Col md={12} sm={24}>
                        <Form.Item label="所属公司">
                          {getFieldDecorator('mdsCompanyId', {
                            rules: [{ required: true, message: '请输入' }],
                            initialValue: details ? details.mdsCompanyId : '',
                          })(
                            <SearchSelect
                              dataUrl="tms/tms-bill/selectSpplierList_s"
                              //   url="tms/tms-oil-card/selectOilVehicleView_s" // selectedData只只有id时需要传url
                              selectedData={this.state.company} // 选中值
                              multiple={false} // 是否多选
                              showValue="customerName"
                              searchName="customerName"
                              allowClear={true}
                              columns={supplierColumns} // 表格展示列
                              onChange={values => this.getValue(values, 'company')} // 获取选中值
                              scrollX={400}
                              disabled={disabled}
                              id="tmsOilCard_3"
                            />
                          )}
                        </Form.Item>
                      </Col>
                    </Row>
                  ) : (
                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                      <Col md={12} sm={24}>
                        <Form.Item label="车辆">
                          {getFieldDecorator('vehicleId', {
                            initialValue: cars,
                            rules: [{ required: true, message: '请输入' }],
                          })(
                            <SearchSelect
                              dataUrl="tms/tms-oil-card/selectOilVehicle"
                              url="tms/tms-oil-card/selectOilVehicleView_s" // selectedData只只有id时需要传url
                              selectedData={cars} // 选中值
                              multiple={false} // 是否多选
                              showValue="cartPlateOneNo"
                              searchName="cartPlate"
                              columns={columns1} // 表格展示列
                              onChange={values => this.getValue(values, 'cars')}
                              scrollX={480}
                              disabled={disabled}
                              id="tmsOilCard_2"
                            />
                          )}
                        </Form.Item>
                      </Col>
                      <Col md={12} sm={24}>
                        <Form.Item label="所属公司">
                          {getFieldDecorator('ownCompanyName', {
                            initialValue: ownCompany
                              ? ownCompany
                              : details && details.ownCompanyName,
                          })(<Input placeholder="请输入" disabled={true} disabled={disabled} />)}
                        </Form.Item>
                      </Col>
                    </Row>
                  )}

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="购买地点">
                        {getFieldDecorator('locationName', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: details ? details.locationName : '',
                        })(<Input placeholder="请输入" disabled={disabled || checkDisabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="购买日期">
                        {getFieldDecorator('happenTime', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue:
                            details && details.happenTime
                              ? moment(details.happenTime, dateFormat)
                              : '',
                        })(<AntdDatePicker disabled={disabled || checkDisabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    {selectCardType == 'SLAVE' && (
                      <Col md={12} sm={24}>
                        <Form.Item label="主卡号">
                          {getFieldDecorator('masterCardNo', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: details ? details.masterCardNo : '',
                          })(
                            <Select
                              placeholder="请选择"
                              allowClear={true}
                              disabled={disabled}
                              //   onChange={values => this.getSellComValue(values, 'sellCompany')}
                              disabled={disabled}
                            >
                              {masterCardList.map(
                                item =>
                                  item.cardNo && <Option key={item.cardNo}>{item.cardNo}</Option>
                              )}
                            </Select>
                          )}
                        </Form.Item>
                      </Col>
                    )}
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <AntdFormItem
                        label="备注"
                        code="remarks"
                        initialValue={details ? details.remarks : ''}
                        getFieldDecorator={getFieldDecorator}
                      >
                        <AntdInput type="textarea" rows={4} disabled={disabled} />
                      </AntdFormItem>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="票据">
                        {getFieldDecorator('fileTokens')(
                          <FileReader disabled={disabled} urlType="tms" />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
export default UpdateForm;
